# -*- coding: utf-8 -*-

from django.db import transaction
from django.core.urlresolvers import reverse, reverse_lazy
from django.contrib import messages
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import redirect
from django.views.generic import FormView, ListView, DetailView, UpdateView, DeleteView, TemplateView
from forms import PostContact, PostCategory
from models import Category, ContactKeeper, Contact, ContactManager


class ContactManagerAddView(FormView):

    template_name = 'contact/contact_collect.html'
    form_class = PostContact

    def get_context_data(self, **kwargs):
        try:
            category = Category.objects.get(id=self.kwargs['pk'])
        except:
            messages.warning(self.request, u'非法请求，所属类别栏目错误')
            return redirect(reverse('category-list'))
        try:
            user = User.objects.get(username=self.kwargs['username'])
        except:
            messages.warning(self.request, u'非法请求，所属用户名错误')
            return redirect(reverse('category-list'))
        category_user = {'category_id': category.id, 'user_id': user.id}
        self.request.session['category_user'] = category_user
        return super(ContactManagerAddView, self).get_context_data(**kwargs)

    def form_valid(self, form):

        category_user = self.request.session.get('category_user', '')
        if category_user:
            user_id = category_user['user_id']
            category_id = category_user['category_id']
            user = User.objects.get(id=user_id)
            category = Category.objects.get(id=category_id)

            with transaction.atomic():
                try:
                    contact = Contact(**form.cleaned_data)
                    contact.save()
                except:
                    messages.warning(self.request, u'新建联系人地址失败')
                    return redirect(reverse('contactmanager-add'))
                contactmanager = ContactManager(
                                            category=category,
                                            contact=contact,
                                            user=user)
                contactmanager.save()
                # todo 重定向感谢界面
                messages.success(self.request, u'新建联系人地址成功')
                return redirect(reverse('category-detail', args=[category_id]))
        return HttpResponse("form valid")


class ContactManagerListView(TemplateView):
    template_name = 'contact/contactmanager_list.html'

    def get_context_data(self, **kwargs):
        contactmanagers = ContactManager.objects.filter(
            category__id=kwargs['category_id'], user=self.request.user)

        return {
            'contactmanagers': contactmanagers
        }

    def dispatch(self, request, *args, **kwargs):
        try:
            Category.objects.get(id=kwargs['category_id'], user=self.request.user)
        except:
            messages.warning(request, u'您无权查看')
            return redirect(reverse('category-list'))
        return super(ContactManagerListView, self).dispatch(request, *args, **kwargs)


class ContactKeeperAddView(FormView):
    template_name = 'contact/contactkeeper_add.html'
    form_class = PostContact

    def form_valid(self, form):

        with transaction.atomic():
            try:
                contact = Contact(**form.cleaned_data)
                contact.save()
            except:
                messages.warning(self.request, u'新建联系人地址失败')
                return redirect(reverse('contactkeeper-add'))
            contactkeeper = ContactKeeper(contact=contact, owner=self.request.user)
            contactkeeper.save()
            messages.success(self.request, u'新建联系人地址成功')
            return redirect(reverse('contactkeeper-list'))


class ContactKeeperListView(ListView):
    template_name = 'contact/contactkeeper_list.html'
    model = ContactKeeper
    context_object_name = 'contactkeepers'

    def get_queryset(self):
        contactkeepers = ContactKeeper.objects.filter(owner=self.request.user)
        return contactkeepers


class ContactKeeperDetailView(DetailView):
    template_name = 'contact/contactkeeper_detail.html'
    model = ContactKeeper
    context_object_name = 'contactkeeper'


class ContactKeeperUpdateView(FormView):
    form_class = PostContact
    template_name = 'contact/contactkeeper_update.html'

    def get_context_data(self, **kwargs):
        contactkeeper = ContactKeeper.objects.get(id=self.kwargs['pk'])
        kwargs.update(dict(contactkeeper=contactkeeper))
        return super(ContactKeeperUpdateView, self).get_context_data(**kwargs)

    def form_valid(self, form):
        try:
            # bug this is to create a new contact
            contact = Contact(**form.cleaned_data)
            contact.save()
            contactkeeper = ContactKeeper(contact=contact, owner=self.request.user)
            contactkeeper.save()
            messages.success(self.request, u'修改更新成功')
            return redirect(reverse('contactkeeper-list'))
        except:
            messages.warning(self.request, u'修改更新失败')
            return redirect(reverse('contactkeeper-list'))


class ContactKeeperDeleteView(DeleteView):
    model = ContactKeeper
    template_name = 'contact/contactkeeper_delete.html'

    def get_success_url(self):
        messages.success(self.request, u'删除成功')
        return reverse('contactkeeper-list')


class CategoryAddView(FormView):

    template_name = 'contact/category_add.html'
    form_class = PostCategory

    def form_valid(self, form):

        name = form.cleaned_data['name']
        description = form.cleaned_data['description']

        try:
            c = Category(name=name, description=description, user=self.request.user)
            c.save()
            messages.success(self.request, u'新建成功')
            return redirect(reverse('category-list'))
        except:
            messages.warning(self.request, u'新建条目失败, 请重新添加')
        return redirect(reverse('category-add'))


class CategoryDeleteView(DeleteView):
    model = Category
    template_name = 'contact/category_delete.html'

    def get_success_url(self):
        messages.success(self.request, u'删除成功')
        return reverse('category-list')


class CategoryUpdateView(UpdateView):
    model = Category
    fields = ['name', 'description']
    template_name = 'contact/category_update.html'

    def get_success_url(self):
        messages.success(self.request, u'修改更新成功')
        return reverse('category-list')


class CategoryListView(ListView):

    template_name = 'contact/category_list.html'
    model = Category
    context_object_name = 'categories'
    paginate_by = 10

    def get_paginate_by(self, queryset):
        return self.request.GET.get('paginate_by', self.paginate_by)


class CategoryDetailView(DetailView):

    template_name = 'contact/category_detail.html'
    model = Category
    context_object_name = 'category'






